package com.ea.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ea.common.constant.BaseNumConstant;
import com.ea.common.constant.RedisKeyConstants;
import com.ea.common.enums.BlockStatusEnums;
import com.ea.common.enums.GoodsStatusEnums;
import com.ea.common.enums.OperationResultCode;
import com.ea.common.enums.ResponseStatusEnums;
import com.ea.common.enums.SysCfgKeyEnums;
import com.ea.common.enums.YesOrNoEnum;
import com.ea.common.exception.ServiceException;
import com.ea.common.util.IdWorker;
import com.ea.common.util.RedisUtil;
import com.ea.domain.dto.ElectricSkuCreateDTO;
import com.ea.domain.dto.ElectricSkuUpdateDTO;
import com.ea.domain.entity.ElectricGoodsInfo;
import com.ea.domain.entity.ElectricGoodsSkuInfo;
import com.ea.domain.entity.InventoryInfo;
import com.ea.domain.entity.SysBaseCfg;
import com.ea.domain.query.BackElectricSkuQueryDTO;
import com.ea.mapper.ElectricGoodsInfoMapper;
import com.ea.mapper.ElectricGoodsSkuInfoMapper;
import com.ea.mapper.InventoryInfoMapper;
import com.ea.service.IEletricGoodsSkuInfoService;
import com.ea.service.ISysBaseCfgService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author NAME-L
 * @Description TODO
 * @className IEletricGoodsSkuInfoServiceImpl
 * @date 2022-12-21 22:23:20
 */
@Service
public class IEletricGoodsSkuInfoServiceImpl implements IEletricGoodsSkuInfoService {
    private static final Logger logger = LoggerFactory.getLogger(IElectricGoodsInfoServiceImpl.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysBaseCfgService sysBaseCfgService;

    @Autowired
    private ElectricGoodsInfoMapper goodsInfoMapper;

    @Autowired
    private ElectricGoodsSkuInfoMapper skuInfoMapper;

    @Autowired
    private InventoryInfoMapper inventoryInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createGoodsSku(List<ElectricSkuCreateDTO> skuCreateDTOList) {
        // 校验是否开启货品规格编码同步规则
        SysBaseCfg sysBaseCfg = sysBaseCfgService.getSysCfgByCfgKey(SysCfgKeyEnums.MODIFY_SKU_BARCODE_SAME_TIME);
        // 批量添加货品规格针对的是同一个货品，所以goodsId是相同的
        Long goodsId = skuCreateDTOList.get(0).getGoodsId();
        ElectricGoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoByGoodsId(goodsId);
        if (BlockStatusEnums.BLOCK_UP.getCode().equals(goodsInfo.getStatus())) {
            throw new ServiceException(OperationResultCode.GOODS_IS_BLOCK_UP);
        }
        List<ElectricGoodsSkuInfo> skuInfoList = new ArrayList<>();
        List<InventoryInfo> inventoryInfoList = new ArrayList<>();
        skuCreateDTOList.forEach(sku -> {
            ElectricGoodsSkuInfo skuInfo = new ElectricGoodsSkuInfo();
            InventoryInfo inventoryInfo = new InventoryInfo();
            BeanUtil.copyProperties(sku, skuInfo);
            skuInfo.setSkuId(IdWorker.nextId());
            skuInfo.setSkuPoint(skuInfo.getSkuPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
            inventoryInfo.setSkuId(skuInfo.getSkuId());
            inventoryInfo.setSkuAmount(BigDecimal.ZERO);
            inventoryInfo.setSkuBarcode(skuInfo.getSkuBarcode());
            inventoryInfo.setSkuName(skuInfo.getSkuName());
            skuInfoList.add(skuInfo);
            inventoryInfoList.add(inventoryInfo);
        });
        // 如果开启了则在规格编号前加上货品编号
        if (YesOrNoEnum.YES.getCode().equals(Integer.valueOf(sysBaseCfg.getCfgValue()))) {
            skuInfoList.forEach(skuInfo -> {
                skuInfo.setSkuBarcode(goodsInfo.getGoodsNo() + "-" + skuInfo.getSkuBarcode() );
            });
        }
        skuInfoMapper.skuInfoBatchInsert(skuInfoList);
        inventoryInfoMapper.insertInventoryBatchList(inventoryInfoList);

    }

    @Override
    public void updateSkuInfo(ElectricSkuUpdateDTO skuUpdateDTO) {
        ElectricGoodsSkuInfo skuInfo = skuInfoMapper.selectOneBySkuId(skuUpdateDTO.getSkuId());
        if (skuInfo == null) {
            throw new ServiceException(OperationResultCode.GOODS_SKU_NO_NOT_EXISTS.getCode(),
                    String.format(OperationResultCode.GOODS_SKU_NO_NOT_EXISTS.getMsg(), skuUpdateDTO.getSkuId()));
        }
        ElectricGoodsSkuInfo goodsSkuInfo = new ElectricGoodsSkuInfo();
        BeanUtil.copyProperties(skuUpdateDTO, goodsSkuInfo);
        // 校验是否开启货品规格编码同步规则
        SysBaseCfg sysBaseCfg = sysBaseCfgService.getSysCfgByCfgKey(SysCfgKeyEnums.MODIFY_SKU_BARCODE_SAME_TIME);
        Long goodsId = skuInfo.getGoodsId();
        ElectricGoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoByGoodsId(goodsId);
        if (YesOrNoEnum.YES.getCode().equals(Integer.valueOf(sysBaseCfg.getCfgValue()))) {
            if (StringUtils.isNotEmpty(skuUpdateDTO.getSkuName())) {
                goodsSkuInfo.setSkuName(goodsInfo.getGoodsName() + skuUpdateDTO.getSkuName());
            }
        }
        skuInfoMapper.updateSkuInfo(goodsSkuInfo);
        // 查询缓存，判断是否完善了规格信息，完善后删除
        try {
            boolean needPerfect = redisUtil.sHasKey(RedisKeyConstants.SYS_NEES_PERFECT_GOODS_SKU, goodsSkuInfo.getSkuId().toString());
            if (needPerfect) {
                redisUtil.setRemove(RedisKeyConstants.SYS_NEES_PERFECT_GOODS_SKU, goodsSkuInfo.getSkuId().toString());
            }
        } catch (ServiceException e) {
            throw new ServiceException(ResponseStatusEnums.ERROR.getCode(), "更新规格信息，删除redisKey失败");
        }
    }

    @Override
    public boolean changeSkuStatus(Long skuId, Integer status) {
        if (skuId == null || status == null) {
            throw new ServiceException(OperationResultCode.PARAMETER_ERROR);
        }
        ElectricGoodsSkuInfo skuInfo = skuInfoMapper.selectOneBySkuId(skuId);
        if (skuInfo == null) {
            return false;
        }
        // 更细状态前判断该货品规格是否允许被修改
        boolean exists = redisUtil.sHasKey(RedisKeyConstants.SYS_NEES_PERFECT_GOODS_SKU, skuId.toString());
        logger.info("getNeedPerfectGoodsSku from redis =====> value: {} ", exists);
        if (exists) {
            throw new ServiceException(OperationResultCode.NEED_UPDATE_GOODS_SKU_INFO.getCode(),
                    String.format(OperationResultCode.NEED_UPDATE_GOODS_SKU_INFO.getMsg(), skuInfo.getSkuBarcode()));
        }
        return skuInfoMapper.updateSkuStatusBySkuId(skuId, status);
    }

    @Override
    public  PageInfo<ElectricGoodsSkuInfo> getSkuList(BackElectricSkuQueryDTO skuQueryDTO) {
        Integer pageIndex = skuQueryDTO.getPageIndex() == null ? BaseNumConstant.NUM_1 : skuQueryDTO.getPageIndex();
        Integer pageSize = skuQueryDTO.getPageSize() == null ? BaseNumConstant.NUM_20 : skuQueryDTO.getPageSize();
        PageHelper.startPage(pageIndex, pageSize);
        List<ElectricGoodsSkuInfo> skuInfoList = skuInfoMapper.selectSkuByCondition(skuQueryDTO);
        return new PageInfo<>(skuInfoList);
    }

    @Override
    public List<ElectricGoodsSkuInfo> getSkuListByGoodsId(Long goodsId) {
        return skuInfoMapper.selectAllByGoodsId(goodsId);
    }


}
